﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.EntityValidation
{
    public class RangeAttribute : ValidationAttribute
    {
      
        public RangeAttribute()
        {
            ErrorMessage = "{0}不在区间内";
        }
        public object Min { get; set; }
        public object Max { get; set; }
        public override bool Verify(object o)
        {

            if(o==null)
            {
                return false;
            }
            var a  = true;
            var b= true;
            if (Min != null && o != null)
            {

                a= Compare(o, Min,o.GetType());
            }

            if (Max != null && o != null)
            {
              b= Compare(Max, o,o.GetType());
            }

            return a && b;
        }
        public bool Compare(object a,object b,Type type)
        {
            var tname = type.Name;
            switch (tname)
            {
                case "Byte":
                    return Convert.ToByte(a) >= Convert.ToByte(b);

           
                case "Int32":
                    return Convert.ToInt32(a) >= Convert.ToInt32(b);
                case "Int64":
                    return Convert.ToInt64(a) >= Convert.ToInt64(b);
                case "UInt16":
                    return Convert.ToUInt16(a) >= Convert.ToUInt16(b);

                case "Decimal":
                    return Convert.ToDecimal(a) >= Convert.ToDecimal(b);
                case "Double":
                    return Convert.ToDouble(a) >= Convert.ToDouble(b);
                case "DateTime":
                    return Convert.ToDateTime(a) >= Convert.ToDateTime(b);
                case "Float":
                    return Convert.ToSingle(a) >= Convert.ToSingle(b);
                case "String":
                    return Convert.ToString(a).CompareTo(Convert.ToString(b))>=0;
            }
            return false;
        }
    }
}